),cT=/^[ -~]{0,255}[!-~]$/,uT=/,|=/;class dT{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){const n=this._clone();return n._internalState.has(e)&&n._internalState.delete(e),n._internalState.set(e,t),n}unset(e){const t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+"="+this.get(t)),e),[]).join(",")}_parse(e){e.length>512||(this._internalState=e.split(",").reverse().reduce((e,t)=>{const n=t.trim(),r=n.indexOf("=");if(-1!==r){const i=n.slice(0,r),o=n.slice(r+1,t.length);(function(e){return aT.test(e)})(i)&&function(e){return cT.test(e)&&!uT.test(e)}(o)&&e.set(i,o)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const e=new dT;return e._internalState=new Map(this._internalState),e}}const fT="traceparent",lT="tracestate",hT=new RegExp("^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$");class pT{inject(e,t,n){const r=dm.getSpanContext(e);if(!r||mm(e)||!tm(r))return;const i=`00-${r.traceId}-${r.spanId}-0${Number(r.traceFlags||By.NONE).toString(16)}`;n.set(t,fT,i),r.traceState&&n.set(t,lT,r.traceState.serialize())}extract(e,t,n){const r=n.get(t,fT);if(!r)return e;const i=Array.isArray(r)?r[0]:r;if("string"!=typeof i)return e;const o=function(e){const t=hT.exec(e);return t?"00"===t[1]&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}:null}(i);if(!o)return e;o.isRemote=!0;const s=n.get(t,lT);if(s){const e=Array.isArray(s)?s.join(","):s;o.traceState=new dT("string"==typeof e?e:void 0)}return dm.setSpanContext(e,o)}fields(){return[fT,lT]}}const gT="baggage";class yT{inject(e,t,n){const r=iT.getBaggage(e);if(!r||mm(e))return;const i=function(e){return e.getAllEntries().map(([e,t])=>{let n=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return void 0!==t.metadata&&(n+=";"+t.metadata.toString()),n})}(r).filter(e=>e.length<=4096).slice(0,180),o=function(e){return e.reduce((e,t)=>{const n=`${e}${""!==e?",":""}${t}`;return n.length>8192?e:n},"")}(i);o.length>0&&n.set(t,gT,o)}extract(e,t,n){const r=n.get(t,gT),i=Array.isArray(r)?r.join(","):r;if(!i)return e;const o={};return 0===i.length?e:(i.split(",").forEach(e=>{const t=function(e){const t=e.split(";");if(t.length<=0)return;const n=t.shift();if(!n)return;const r=n.indexOf("=");if(r<=0)return;const i=decodeURIComponent(n.substring(0,r).trim()),o=decodeURIComponent(n.substring(r+1).trim());let s;return t.length>0&&("string"!=typeof(a=t.join(";"))&&(eT.error("Cannot create baggage metadata from unknown type: "+typeof a),a=""),s={__TYPE__:Q_,toString:function(){return a}}),{key:i,value:o,metadata:s};var a}(e);if(t){const e={value:t.value};t.metadata&&(e.metadata=t.metadata),o[t.key]=e}}),0===Object.entries(o).length?e:iT.setBaggage(e,iT.createBaggage(o)))}fields(){return[gT]}}class mT extends q_{constructor(e={}){super(e)}register(e={}){var t;dm.setGlobalTracerProvider(this),null!==(t=e.propagator)&&(void 0!==t?iT.setGlobalPropagator(t):iT.setGlobalPropagator(new oT({propagators:[new pT,new yT]}))),function(e){if(null!==e){if(void 0===e){const e=new H_;return e.enable(),void gm.setGlobalContextManager(e)}e.enable(),gm.setGlobalContextManager(e)}}(e.contextManager)}}var bT,wT=(bT=function(e,t){return bT=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},bT(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}bT(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),vT=function(){function e(){}return e.prototype.createGauge=function(e,t){return OT},e.prototype.createHistogram=function(e,t){return CT},e.prototype.createCounter=function(e,t){return RT},e.prototype.createUpDownCounter=function(e,t){return KT},e.prototype.createObservableGauge=function(e,t){return BT},e.prototype.createObservableCounter=function(e,t){return UT},e.prototype.createObservableUpDownCounter=function(e,t){return MT},e.prototype.addBatchObservableCallback=function(e,t){},e.prototype.removeBatchObservableCallback=function(e){},e}(),ST=function(){},_T=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return wT(t,e),t.prototype.add=function(e,t){},t}(ST),TT=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return wT(t,e),t.prototype.add=function(e,t){},t}(ST),kT=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return wT(t,e),t.prototype.record=function(e,t){},t}(ST),xT=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return wT(t,e),t.prototype.record=function(e,t){},t}(ST),IT=function(){function e(){}return e.prototype.addCallback=function(e){},e.prototype.removeCallback=function(e){},e}(),ET=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return wT(t,e),t}(IT),AT=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return wT(t,e),t}(IT),PT=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return wT(t,e),t}(IT),NT=new vT,RT=new _T,OT=new kT,CT=new xT,KT=new TT,UT=new ET,BT=new AT,MT=new PT,LT=new(function(){function e(){}return e.prototype.getMeter=function(e,t,n){return NT},e}()),JT="metrics",DT=function(){function e(){}return e.getInstance=function(){return this._instance||(this._instance=new e),this._instance},e.prototype.setGlobalMeterProvider=function(e){return Ey(JT,e,My.instance())},e.prototype.getMeterProvider=function(){return Ay(JT)||LT},e.prototype.getMeter=function(e,t,n){return this.getMeterProvider().getMeter(e,t,n)},e.prototype.disable=function(){Py(JT,My.instance())},e}().getInstance();const FT="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof s.g?s.g:{},qT=Symbol.for("io.opentelemetry.js.api.logs"),HT=FT;class $T{emit(e){}}const jT=new $T,VT=new class{getLogger(e,t,n){return new $T}};class zT{constructor(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):jT}}class GT{getLogger(e,t,n){var r;return null!==(r=this.getDelegateLogger(e,t,n))&&void 0!==r?r:new zT(this,e,t,n)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:VT}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,n){var r;return null===(r=this._delegate)||void 0===r?void 0:r.getLogger(e,t,n)}}class WT{constructor(){this._proxyLoggerProvider=new GT}static getInstance(){return this._instance||(this._instance=new WT),this._instance}setGlobalLoggerProvider(e){return HT[qT]?this.getLoggerProvider():(HT[qT]=(t=e,n=VT,e=>1===e?t:n),this._proxyLoggerProvider.setDelegate(e),e);var t,n}getLoggerProvider(){var e,t;return null!==(t=null===(e=HT[qT])||void 0===e?void 0:e.call(HT,1))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,n){return this.getLoggerProvider().getLogger(e,t,n)}disable(){delete HT[qT],this._proxyLoggerProvider=new GT}}const ZT=WT.getInstance();let YT=console.error.bind(console);function XT(e,t,n){const r=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:r,writable:!0,value:n})}const QT=(e,t,n)=>{if(!e||!e[t])return void YT("no original function "+String(t)+" to wrap");if(!n)return YT("no wrapper function"),void YT((new Error).stack);const r=e[t];if("function"!=typeof r||"function"!=typeof n)return void YT("original object and wrapper must be functions");const i=n(r,t);return XT(i,"__original",r),XT(i,"__unwrap",()=>{e[t]===i&&XT(e,t,r)}),XT(i,"__wrapped",!0),XT(e,t,i),i},ek=(e,t,n)=>{if(!e)return YT("must provide one or more modules to patch"),void YT((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{QT(e,t,n)})}):YT("must provide one or more functions to wrap on modules")},tk=(e,t)=>{if(!e||!e[t])return YT("no function to unwrap."),void YT((new Error).stack);const n=e[t];n.__unwrap?n.__unwrap():YT("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},nk=(e,t)=>{if(!e)return YT("must provide one or more modules to patch"),void YT((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{tk(e,t)})}):YT("must provide one or more functions to unwrap on modules")};function rk(e){e&&e.logger&&("function"!=typeof e.logger?YT("new logger isn't a function, not replacing"):YT=e.logger)}rk.wrap=QT,rk.massWrap=ek,rk.unwrap=tk,rk.massUnwrap=nk;class ik{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(e,t,n){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(n),this._diag=hm.createComponentLogger({namespace:e}),this._tracer=dm.getTracer(e,t),this._meter=DT.getMeter(e,t),this._logger=ZT.getLogger(e,t),this._updateMetricInstruments()}_wrap=QT;_unwrap=tk;_massWrap=ek;_massUnwrap=nk;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,n,r){if(e)try{e(n,r)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}}class ok extends ik{constructor(e,t,n){super(e,t,n),this._config.enabled&&this.enable()}}var sk;function ak(e,t,n){let r,i;try{i=e()}catch(e){r=e}finally{if(t(r,i),r&&!n)throw r;return i}}function ck(e,t){return"string"==typeof t?e===t:!!e.match(t)}!function(e){e[e.STABLE=1]="STABLE",e[e.OLD=2]="OLD",e[e.DUPLICATE=3]="DUPLICATE"}(sk||(sk={}));const uk=performance,dk=Math.pow(10,6),fk=Math.pow(10,9);function lk(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*dk)]}function hk(e){return function(e,t){const n=[e[0]+t[0],e[1]+t[1]];return n[1]>=fk&&(n[1]-=fk,n[0]+=1),n}(lk(function(){let e=uk.timeOrigin;if("number"!=typeof e){const t=uk;e=t.timing&&t.timing.fetchStart}return e}()),lk("number"==typeof e?e:uk.now()))}var pk;!function(e){e.CONNECT_END="connectEnd",e.CONNECT_START="connectStart",e.DECODED_BODY_SIZE="decodedBodySize",e.DOM_COMPLETE="domComplete",e.DOM_CONTENT_LOADED_EVENT_END="domContentLoadedEventEnd",e.DOM_CONTENT_LOADED_EVENT_START="domContentLoadedEventStart",e.DOM_INTERACTIVE="domInteractive",e.DOMAIN_LOOKUP_END="domainLookupEnd",e.DOMAIN_LOOKUP_START="domainLookupStart",e.ENCODED_BODY_SIZE="encodedBodySize",e.FETCH_START="fetchStart",e.LOAD_EVENT_END="loadEventEnd",e.LOAD_EVENT_START="loadEventStart",e.NAVIGATION_START="navigationStart",e.REDIRECT_END="redirectEnd",e.REDIRECT_START="redirectStart",e.REQUEST_START="requestStart",e.RESPONSE_END="responseEnd",e.RESPONSE_START="responseStart",e.SECURE_CONNECTION_START="secureConnectionStart",e.START_TIME="startTime",e.UNLOAD_EVENT_END="unloadEventEnd",e.UNLOAD_EVENT_START="unloadEventStart"}(pk||(pk={}));const gk=performance,yk=Math.pow(10,6),mk=Math.pow(10,9);function bk(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*yk)]}function wk(){let e=gk.timeOrigin;if("number"!=typeof e){const t=gk;e=t.timing&&t.timing.fetchStart}return e}function vk(e){if(t=e,Array.isArray(t)&&2===t.length&&"number"==typeof t[0]&&"number"==typeof t[1])return e;var t,n;if("number"==typeof e)return e=mk&&(n[1]-=mk,n[0]+=1),n}(bk(wk()),bk("number"==typeof n?n:gk.now()))):bk(e);if(e instanceof Date)return bk(e.getTime());throw TypeError("Invalid input type")}function Sk(e){return e[0]*mk+e[1]}let _k;function Tk(e,t,n,r=!0){if(t in n&&"number"==typeof n[t]&&(!r||0!==n[t]))return e.addEvent(t,n[t])}function kk(e,t,n=!1,r,i){if(void 0===r&&(r=0!==t[pk.START_TIME]),n||(Tk(e,pk.FETCH_START,t,r),Tk(e,pk.DOMAIN_LOOKUP_START,t,r),Tk(e,pk.DOMAIN_LOOKUP_END,t,r),Tk(e,pk.CONNECT_START,t,r),Tk(e,pk.SECURE_CONNECTION_START,t,r),Tk(e,pk.CONNECT_END,t,r),Tk(e,pk.REQUEST_START,t,r),Tk(e,pk.RESPONSE_START,t,r),Tk(e,pk.RESPONSE_END,t,r)),!i){const n=t[pk.ENCODED_BODY_SIZE];void 0!==n&&e.setAttribute("http.response_content_length",n);const r=t[pk.DECODED_BODY_SIZE];void 0!==r&&n!==r&&e.setAttribute("http.response_content_length_uncompressed",r)}}function xk(){return"undefined"!=typeof location?location.origin:void 0}function Ik(e){if("function"==typeof URL)return new URL(e,"undefined"!=typeof document?document.baseURI:"undefined"!=typeof location?location.href:void 0);const t=(_k||(_k=document.createElement("a")),_k);return t.href=e,t}var Ek;!function(e){e.COMPONENT="component",e.HTTP_STATUS_TEXT="http.status_text"}(Ek||(Ek={}));var Ak=s(7805);const Pk=hm.createComponentLogger({namespace:"@opentelemetry/opentelemetry-instrumentation-fetch/utils"});const Nk=new TextEncoder;function Rk(e){return Nk.encode(e).byteLength}const Ok={CONNECT:!0,DELETE:!0,GET:!0,HEAD:!0,OPTIONS:!0,PATCH:!0,POST:!0,PUT:!0,TRACE:!0};let Ck;function Kk(){if(void 0===Ck){const e=void 0;e&&e.length>0?(Ck={},e.forEach(e=>{Ck[e]=!0})):Ck=Ok}return Ck}const Uk={"https:":"443","http:":"80"},Bk="0.203.0",Mk="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof s.g?s.g:{},Lk="object"==typeof process&&"node"===process.release?.name;class Jk extends ok{component="fetch";version=Bk;moduleName=this.component;_usedResources=new WeakSet;_tasksCount=0;_semconvStability;constructor(e={}){super("@opentelemetry/instrumentation-fetch",Bk,e),this._semconvStability=function(e,t){let n=sk.OLD;const r=t?.split(",").map(e=>e.trim()).filter(e=>""!==e);for(const t of r??[]){if(t.toLowerCase()===e+"/dup"){n=sk.DUPLICATE;break}t.toLowerCase()===e&&(n=sk.STABLE)}return n}("http",e?.semconvStabilityOptIn)}init(){}_addChildSpan(e,t){const n=this.tracer.startSpan("CORS Preflight",{startTime:t[pk.FETCH_START]},dm.setSpan(gm.active(),e)),r=!(this._semconvStability&sk.OLD);kk(n,t,this.getConfig().ignoreNetworkEvents,void 0,r),n.end(t[pk.RESPONSE_END])}_addFinalSpanAttributes(e,t){const n=Ik(t.url);if(this._semconvStability&sk.OLD&&(e.setAttribute(Ak.a3,t.status),null!=t.statusText&&e.setAttribute(Ek.HTTP_STATUS_TEXT,t.statusText),e.setAttribute(Ak.Mm,n.host),e.setAttribute(Ak.v8,n.protocol.replace(":","")),"undefined"!=typeof navigator&&e.setAttribute(Ak.ds,navigator.userAgent)),this._semconvStability&sk.STABLE){e.setAttribute("http.response.status_code",t.status),e.setAttribute("server.address",n.hostname);const r=function(e){const t=Number(e.port||Uk[e.protocol]);return t&&!isNaN(t)?t:void 0}(n);r&&e.setAttribute("server.port",r)}}_addHeaders(e,t){if(!function(e,t){let n=t||[];return("string"==typeof n||n instanceof RegExp)&&(n=[n]),Ik(e).origin===xk()||n.some(t=>{return n=e,"string"==typeof(r=t)?n===r:!!n.match(r);var n,r})}(t,this.getConfig().propagateTraceHeaderCorsUrls)){const e={};return iT.inject(gm.active(),e),void(Object.keys(e).length>0&&this._diag.debug("headers inject skipped due to CORS policy"))}if(e instanceof Request)iT.inject(gm.active(),e.headers,{set:(e,t,n)=>e.set(t,"string"==typeof n?n:String(n))});else if(e.headers instanceof Headers)iT.inject(gm.active(),e.headers,{set:(e,t,n)=>e.set(t,"string"==typeof n?n:String(n))});else if(e.headers instanceof Map)iT.inject(gm.active(),e.headers,{set:(e,t,n)=>e.set(t,"string"==typeof n?n:String(n))});else{const t={};iT.inject(gm.active(),t),e.headers=Object.assign({},t,e.headers||{})}}_clearResources(){0===this._tasksCount&&this.getConfig().clearTimingResources&&(performance.clearResourceTimings(),this._usedResources=new WeakSet)}_createSpan(e,t={}){if(function(e,t){if(!t)return!1;for(const n of t)if(ck(e,n))return!0;return!1}(e,this.getConfig().ignoreUrls))return void this._diag.debug("ignoring span as url matches ignored url");let n="";const r={};if(this._semconvStability&sk.OLD){const i=(t.method||"GET").toUpperCase();n=`HTTP ${i}`,r[Ek.COMPONENT]=this.moduleName,r[Ak.rp]=i,r[Ak.XV]=e}if(this._semconvStability&sk.STABLE){const i=t.method,o=function(e){const t=Kk(),n=e.toUpperCase();return n in t?n:"_OTHER"}(t.method||"GET");n||(n=o),r["http.request.method"]=o,o!==i&&(r["http.request.method_original"]=i),r["url.full"]=e}return this.tracer.startSpan(n,{kind:b_.CLIENT,attributes:r})}_findResourceAndAddNetworkEvents(e,t,n){let r=t.entries;if(!r.length){if(!performance.getEntriesByType)return;r=performance.getEntriesByType("resource")}const i=function(e,t,n,r,i=new WeakSet,o){const s=Ik(e),a=function(e,t,n,r,i,o){const s=Sk(t),a=Sk(n);let c=r.filter(t=>{const n=Sk(vk(t[pk.FETCH_START])),r=Sk(vk(t[pk.RESPONSE_END]));return t.initiatorType.toLowerCase()===(o||"xmlhttprequest")&&t.name===e&&n>=s&&r<=a});return c.length>0&&(c=c.filter(e=>!i.has(e))),c}(e=s.toString(),t,n,r,i,o);if(0===a.length)return{mainRequest:void 0};if(1===a.length)return{mainRequest:a[0]};const c=function(e){return e.slice().sort((e,t)=>{const n=e[pk.FETCH_START],r=t[pk.FETCH_START];return n>r?1:n1){let e=c[0],t=function(e,t,n){const r=Sk(n),i=Sk(vk(t));let o,s=e[1];const a=e.length;for(let t=1;t=i&&(!o||c=400&&(e.setStatus({code:v_.ERROR}),e.setAttribute("error.type",String(n.status))),setTimeout(()=>{t.observer?.disconnect(),this._findResourceAndAddNetworkEvents(e,t,i),this._tasksCount--,this._clearResources(),e.end(r)},300)}_patchConstructor(){return e=>{const t=this;return function(...n){const r=this,i=Ik(n[0]instanceof Request?n[0].url:String(n[0])).href,o=n[0]instanceof Request?n[0]:n[1]||{},s=t._createSpan(i,o);if(!s)return e.apply(this,n);const a=t._prepareSpanData(i);function c(e,n){t._applyAttributesAfterFetch(e,o,n),t._endSpan(e,a,{status:n.status||0,statusText:n.message,url:i})}function u(e,n){t._applyAttributesAfterFetch(e,o,n),n.status>=200&&n.status<400?t._endSpan(e,a,n):t._endSpan(e,a,{status:n.status,statusText:n.statusText,url:i})}function d(e,t,n){try{const t=n.clone().body;if(t){const r=t.getReader(),i=()=>{r.read().then(({done:t})=>{t?u(e,n):i()},t=>{c(e,t)})};i()}else u(e,n)}finally{t(n)}}function f(e,t,n){try{c(e,n)}finally{t(n)}}return t.getConfig().measureRequestSize&&function(...e){if(e[0]instanceof URL||"string"==typeof e[0]){const n=e[1];if(!n?.body)return Promise.resolve();if(n.body instanceof ReadableStream){const{body:e,length:t}=function(e){if(!e.pipeThrough)return Pk.warn("Platform has ReadableStream but not pipeThrough!"),{body:e,length:Promise.resolve(void 0)};let t,n=0;const r=new Promise(e=>{t=e}),i=new TransformStream({start(){},async transform(e,t){const r=await e;n+=r.byteLength,t.enqueue(e)},flush(){t(n)}});return{body:e.pipeThrough(i),length:r}}(n.body);return n.body=e,t}return Promise.resolve((t=n.body,"undefined"!=typeof Document&&t instanceof Document?(new XMLSerializer).serializeToString(document).length:"string"==typeof t?Rk(t):t instanceof Blob?t.size:t instanceof FormData?function(e){let t=0;for(const[n,r]of e.entries())t+=n.length,r instanceof Blob?t+=r.size:t+=r.length;return t}(t):t instanceof URLSearchParams?Rk(t.toString()):void 0!==t.byteLength?t.byteLength:void Pk.warn("unknown body type")))}var t;{const t=e[0];return t?.body?t.clone().text().then(e=>Rk(e)):Promise.resolve()}}(...n).then(e=>{e&&(t._semconvStability&sk.OLD&&s.setAttribute(Ak.z4,e),t._semconvStability&sk.STABLE&&s.setAttribute(Ak.Me,e))}).catch(e=>{t._diag.warn("getFetchBodyLength",e)}),new Promise((n,a)=>gm.with(dm.setSpan(gm.active(),s),()=>(t._addHeaders(o,i),t._callRequestHook(s,o),t._tasksCount++,e.apply(r,o instanceof Request?[o]:[i,o]).then(d.bind(r,s,n),f.bind(r,s,a)))))}}}_applyAttributesAfterFetch(e,t,n){const r=this.getConfig().applyCustomAttributesOnSpan;r&&ak(()=>r(e,t,n),e=>{e&&this._diag.error("applyCustomAttributesOnSpan",e)},!0)}_callRequestHook(e,t){const n=this.getConfig().requestHook;n&&ak(()=>n(e,t),e=>{e&&this._diag.error("requestHook",e)},!0)}_prepareSpanData(e){const t=hk(),n=[];if("function"!=typeof PerformanceObserver)return{entries:n,startTime:t,spanUrl:e};const r=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{"fetch"===t.initiatorType&&t.name===e&&n.push(t)})});return r.observe({entryTypes:["resource"]}),{entries:n,observer:r,startTime:t,spanUrl:e}}enable(){var e;Lk?this._diag.warn("this instrumentation is intended for web usage only, it does not instrument Node.js's fetch()"):("function"==typeof(e=fetch)&&"function"==typeof e.__original&&"function"==typeof e.__unwrap&&!0===e.__wrapped&&(this._unwrap(Mk,"fetch"),this._diag.debug("removing previous patch for constructor")),this._wrap(Mk,"fetch",this._patchConstructor()))}disable(){Lk||(this._unwrap(Mk,"fetch"),this._usedResources=new WeakSet)}}var Dk=class extends jv{transport;constructor(e,t=(0,$S.FetchTransport)()){super(e),this.transport=t}async createChannelWithTLS(e){try{return(0,$S.createChannel)(e,this.transport)}catch(t){throw console.error("Channel creation error:",t),new Km("Failed to create channel",{url:e,operation:"createChannel",errorCount:1,errors:t instanceof Error?t.message:String(t)},t)}}createAuthnMiddleware(){return async function*(e,t){const n=(0,Qg.Metadata)(t.metadata).set("X-Requested-With","XMLHttpRequest").set("X-Grpc-Web","1").set("X-Client-Env",gv).set("Content-Type","application/grpc-web+proto");return yield*e.next(e.request,{...t,metadata:n})}.bind(this)}createMiddleware(e){return async function*(t,n){const r=(0,Qg.Metadata)(n.metadata).set("X-Requested-With","XMLHttpRequest").set("X-Grpc-Web","1").set("X-Client-Env",gv).set("Content-Type","application/grpc-web+proto");try{const i=await this.authenticate(e);return yield*t.next(t.request,{...n,metadata:r.set("Authorization",`Bearer ${i}`)})}catch(i){return yield*this.handleMiddlewareError(i,e,t,r,n)}}.bind(this)}async createGrpcClient(e,t,n,r,i){let o;let s={};return o=(0,$S.createClientFactory)(),n&&(s={retry:!0,retryMaxAttempts:3},o=o.use(jS.D)),r&&(o=o.use(r)),{...o.create(e,t,{"*":s}),close:i?()=>jv.releaseChannel(i):void 0}}},Fk=class extends DS{buildConnectionManager(e){return new Dk(e)}initializeTracerEnv({spanProcessors:e,traceUrls:t}){!function({spanProcessors:e,traceUrls:t}){new mT({spanProcessors:e}).register(),iT.setGlobalPropagator(new pT),function(e){const t=e.tracerProvider||dm.getTracerProvider(),n=e.meterProvider||DT.getMeterProvider(),r=e.loggerProvider||ZT.getLoggerProvider();!function(e,t,n,r){for(let i=0,o=e.length;ie.replace(/[.*+?^${}()|[\]\\]/g,"\\")).join("|")}))`)],propagateTraceHeaderCorsUrls:/.*/})]})}({spanProcessors:e,traceUrls:t})}};function qk(e,t=""){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t&&`"${t}" `}expected integer >= 0, got ${e}`)}function Hk(e,t,n=""){const r=(i=e)instanceof Uint8Array||ArrayBuffer.isView(i)&&"Uint8Array"===i.constructor.name;var i;const o=e?.length,s=void 0!==t;if(!r||s&&o!==t)throw new Error((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${o}`:"type="+typeof e));return e}function $k(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash must wrapped by utils.createHasher");qk(e.outputLen),qk(e.blockLen)}function jk(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Vk(...e){for(let t=0;t>>t}const Wk=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Zk=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Yk(e,t={}){const n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}const Xk=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Qk(e,t,n){return e&t^~e&n}function ex(e,t,n){return e&t^e&n^t&n}class tx{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=zk(this.buffer)}update(e){jk(this),Hk(e);const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let o=0;o='+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;t[o++]=128,Vk(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let e=o;eu.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e>>3,i=Gk(n,17)^Gk(n,19)^n>>>10;ix[e]=i+ix[e-7]+r+ix[e-16]|0}let{A:n,B:r,C:i,D:o,E:s,F:a,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(Gk(s,6)^Gk(s,11)^Gk(s,25))+Qk(s,a,c)+rx[e]+ix[e]|0,d=(Gk(n,2)^Gk(n,13)^Gk(n,22))+ex(n,r,i)|0;u=c,c=a,a=s,s=o+t|0,o=i,i=r,r=n,n=t+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,r,i,o,s,a,c,u)}roundClean(){Vk(ix)}destroy(){this.set(0,0,0,0,0,0,0,0),Vk(this.buffer)}}class sx extends ox{A=0|nx[0];B=0|nx[1];C=0|nx[2];D=0|nx[3];E=0|nx[4];F=0|nx[5];G=0|nx[6];H=0|nx[7];constructor(){super(32)}}const ax=Yk(()=>new sx,Xk(1));function cx(e){const t="string"==typeof e?function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e):e,n=function(e){if(Hk(e),Wk)return e.toHex();let t="";for(let n=0;nn?e.create().update(t).digest():t);for(let e=0;enew dx(e,t).update(n).digest();fx.create=(e,t)=>new dx(e,t);const lx=Uint8Array.of(0),hx=Uint8Array.of(),px={p:0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,n:0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,h:1n,a:0n,b:7n,Gx:0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Gy:0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n},{p:gx,n:yx,Gx:mx,Gy:bx,b:wx}=px,vx={publicKey:33,publicKeyUncompressed:65,signature:64,seed:48},Sx=(e="")=>{const t=new Error(e);throw((...e)=>{"captureStackTrace"in Error&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(...e)})(t,Sx),t},_x=(e,t,n="")=>{const r=(i=e)instanceof Uint8Array||ArrayBuffer.isView(i)&&"Uint8Array"===i.constructor.name;var i;const o=e?.length,s=void 0!==t;return(!r||s&&o!==t)&&Sx((n&&`"${n}" `)+"expected Uint8Array"+(s?` of length ${t}`:"")+", got "+(r?`length=${o}`:"type="+typeof e)),e},Tx=e=>new Uint8Array(e),kx=(e,t)=>e.toString(16).padStart(t,"0"),xx=e=>Array.from(_x(e)).map(e=>kx(e,2)).join(""),Ix=e=>e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0,Ex=e=>{const t="hex invalid";if("string"!=typeof e)return Sx(t);const n=e.length,r=n/2;if(n%2)return Sx(t);const i=Tx(r);for(let n=0,o=0;n{const t=Tx(e.reduce((e,t)=>e+_x(t).length,0));let n=0;return e.forEach(e=>{t.set(e,n),n+=e.length}),t},Px=(e=32)=>(globalThis?.crypto).getRandomValues(Tx(e)),Nx=BigInt,Rx=(e,t,n,r="bad number: out of range")=>(e=>"bigint"==typeof e)(e)&&t<=e&&e{const n=e%t;return n>=0n?n:t+n},Cx=e=>e instanceof Jx?e:Sx("Point expected"),Kx=e=>Ox(Ox(e*e)*e+wx),Ux=e=>Rx(e,0n,gx),Bx=e=>Rx(e,1n,gx),Mx=e=>0n==(1n&e),Lx=e=>Uint8Array.of(e);class Jx{static BASE;static ZERO;X;Y;Z;constructor(e,t,n){this.X=Ux(e),this.Y=Bx(t),this.Z=Ux(n),Object.freeze(this)}static CURVE(){return px}static fromAffine(e){const{x:t,y:n}=e;return 0n===t&&0n===n?Fx:new Jx(t,n,1n)}static fromBytes(e){_x(e);const{publicKey:t,publicKeyUncompressed:n}=vx;let r;const i=e.length,o=e[0],s=e.subarray(1),a=Hx(s,0,32);if(i===t&&(2===o||3===o)){let e=(e=>{const t=Kx(Bx(e));let n=1n;for(let e=t,r=(gx+1n)/4n;r>0n;r>>=1n)1n&r&&(n=n*e%gx),e=e*e%gx;return Ox(n*n)===t?n:Sx("sqrt invalid")})(a);const t=Mx(e);Mx(Nx(o))!==t&&(e=Ox(-e)),r=new Jx(a,e,1n)}return i===n&&4===o&&(r=new Jx(a,Hx(s,32,64),1n)),r?r.assertValidity():Sx("bad point: not on curve")}static fromHex(e){return Jx.fromBytes(Ex(e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(e){const{X:t,Y:n,Z:r}=this,{X:i,Y:o,Z:s}=Cx(e),a=Ox(t*s),c=Ox(i*r),u=Ox(n*s),d=Ox(o*r);return a===c&&u===d}is0(){return this.equals(Fx)}negate(){return new Jx(this.X,Ox(-this.Y),this.Z)}double(){return this.add(this)}add(e){const{X:t,Y:n,Z:r}=this,{X:i,Y:o,Z:s}=Cx(e);let a=0n,c=0n,u=0n;const d=Ox(3n*wx);let f=Ox(t*i),l=Ox(n*o),h=Ox(r*s),p=Ox(t+n),g=Ox(i+o);p=Ox(p*g),g=Ox(f+l),p=Ox(p-g),g=Ox(t+r);let y=Ox(i+s);return g=Ox(g*y),y=Ox(f+h),g=Ox(g-y),y=Ox(n+r),a=Ox(o+s),y=Ox(y*a),a=Ox(l+h),y=Ox(y-a),u=Ox(0n*g),a=Ox(d*h),u=Ox(a+u),a=Ox(l-u),u=Ox(l+u),c=Ox(a*u),l=Ox(f+f),l=Ox(l+f),h=Ox(0n*h),g=Ox(d*g),l=Ox(l+h),h=Ox(f-h),h=Ox(0n*h),g=Ox(g+h),f=Ox(l*g),c=Ox(c+f),f=Ox(y*g),a=Ox(p*a),a=Ox(a-f),f=Ox(p*l),u=Ox(y*u),u=Ox(u+f),new Jx(a,c,u)}subtract(e){return this.add(Cx(e).negate())}multiply(e,t=!0){if(!t&&0n===e)return Fx;if((e=>{Rx(e,1n,yx)})(e),1n===e)return this;if(this.equals(Dx))return Qx(e).p;let n=Fx,r=Dx;for(let i=this;e>0n;i=i.double(),e>>=1n)1n&e?n=n.add(i):t&&(r=r.add(i));return n}multiplyUnsafe(e){return this.multiply(e,!1)}toAffine(){const{X:e,Y:t,Z:n}=this;if(this.equals(Fx))return{x:0n,y:0n};if(1n===n)return{x:e,y:t};const r=((e,t)=>{(0n===e||t<=0n)&&Sx("no inverse n="+e+" mod="+t);let n=Ox(e,t),r=t,i=0n,o=1n,s=1n,a=0n;for(;0n!==n;){const e=r/n,t=r%n,c=i-s*e,u=o-a*e;r=n,n=t,i=s,o=a,s=c,a=u}return 1n===r?Ox(i,t):Sx("no inverse")})(n,gx);return 1n!==Ox(n*r)&&Sx("inverse invalid"),{x:Ox(e*r),y:Ox(t*r)}}assertValidity(){const{x:e,y:t}=this.toAffine();return Bx(e),Bx(t),Ox(t*t)===Kx(e)?this:Sx("bad point: not on curve")}toBytes(e=!0){const{x:t,y:n}=this.assertValidity().toAffine(),r=jx(t);return e?Ax((e=>Lx(Mx(e)?2:3))(n),r):Ax(Lx(4),r,jx(n))}toHex(e){return xx(this.toBytes(e))}}const Dx=new Jx(mx,bx,1n),Fx=new Jx(0n,1n,0n);Jx.BASE=Dx,Jx.ZERO=Fx;const qx=e=>Nx("0x"+(xx(e)||"0")),Hx=(e,t,n)=>qx(e.subarray(t,n)),$x=2n**256n,jx=e=>Ex(kx(Rx(e,0n,$x),64)),Vx=e=>{const t=qx(_x(e,32,"secret key"));return Rx(t,1n,yx,"invalid secret key: outside of range")},zx=(e,t=!0)=>Dx.multiply(Vx(e)).toBytes(t);Tx(0),Lx(0),Lx(1);const Gx=e=>t=>{const n=((e=Px(vx.seed))=>{_x(e),(e.length1024)&&Sx("expected 40-1024b");const t=Ox(qx(e),yx-1n);return jx(t+1n)})(t);return{secretKey:n,publicKey:e(n)}},Wx=(Gx(zx),e=>{const t=Vx(e),n=Dx.multiply(t),{x:r,y:i}=n.assertValidity().toAffine();return{d:Mx(i)?t:(o=-t,Ox(o,yx)),px:jx(r)};var o}),Zx=(Gx(e=>Wx(e).px),Math.ceil(32)+1);let Yx;const Xx=(e,t)=>{const n=t.negate();return e?n:t},Qx=e=>{const t=Yx||(Yx=(()=>{const e=[];let t=Dx,n=t;for(let r=0;r>=o,a>128&&(a-=256,e+=1n);const c=128*s,u=c,d=c+Math.abs(a)-1,f=s%2!=0,l=a<0;0===a?r=r.add(Xx(f,t[u])):n=n.add(Xx(l,t[d]))}return 0n!==e&&Sx("invalid wnaf"),{p:n,f:r}};var eI=s(8287).hp,tI=s(8287).hp;const nI=e=>{if(e instanceof Uint8Array)return e;if("string"!=typeof e)throw new Error("Expected hex string or Uint8Array");const t=new Uint8Array(e.length/2);for(let n=0;n{let t="";const n=new Uint8Array(e),r=n.byteLength;for(let e=0;eJx.fromBytes(t).multiply(Vx(e)).toBytes(n))(nI(r),nI(i),!0).slice(1,33);return s=ax,a=o,c=new Uint8Array(0),u=(new TextEncoder).encode("ecdh-aes-key:"+n),d=32,function(e,t,n,r=32){$k(e),qk(r,"length");const i=e.outputLen;if(r>255*i)throw new Error("Length must be <= 255*HashLen");const o=Math.ceil(r/i);void 0===n?n=hx:Hk(n,void 0,"info");const s=new Uint8Array(o*i),a=fx.create(e,t),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let e=0;e{const n={},r=e=>{const t=n[e];if(!t)throw new Error("sparkWallet not initialized");return t},i=async(n,r)=>{const i={incomingPayment:!0,result:JSON.stringify({transferId:n,balance:r.toString()}),isResponse:!0};try{const n=await oI(e,JSON.stringify(i));t.postMessage(JSON.stringify({encrypted:n}))}catch(e){console.log("Encryption error during handleTransfer:",e)}};return{initializeSparkWallet:async({mnemonic:e})=>{try{const t=(e=>cx(e))(e);if(n[t])return{isConnected:!0};const{wallet:r}=await Fk.initialize({mnemonicOrSeed:e,options:{network:"MAINNET",optimizationOptions:{multiplicity:2,auto:!0}}});return e=null,n[t]=r,{isConnected:!0}}catch(e){return console.log("Initialize spark wallet error function",e),{isConnected:!1,error:e.message}}},removeWalletEventListener:({mnemonic:e})=>{const t=r(e);t?.listenerCount("transfer:claimed")&&t.removeAllListeners("transfer:claimed")},addWalletEventListener:({mnemonic:e})=>{const t=r(e);t?.listenerCount("transfer:claimed")||t.on("transfer:claimed",i)},getSparkIdentityPubKey:async({mnemonic:e})=>{try{return await r(e).getIdentityPublicKey()}catch(e){console.log("Get spark identity public key error",e)}},getSparkBalance:async({mnemonic:e})=>{try{const t=r(e),n=await t.getBalance();let i={};for(const[e,t]of n.tokenBalances)i[e]={...t,tokenMetadata:{...t.tokenMetadata,maxSupply:t.tokenMetadata.maxSupply.toString()},balance:t.balance.toString()};return{tokensObject:i,balance:n.balance.toString(),didWork:!0}}catch(e){return console.log("Get spark balance error",e),{didWork:!1}}},getSparkStaticBitcoinL1Address:async({mnemonic:e})=>{try{return await r(e).getStaticDepositAddress()}catch(e){console.log("Get reusable Bitcoin mainchain address error",e)}},queryAllStaticDepositAddresses:async({mnemonic:e})=>{try{return await r(e).queryStaticDepositAddresses()}catch(e){console.log("Query reusable Bitcoin mainchain addresses error",e)}},getSparkStaticBitcoinL1AddressQuote:async({txid:e,mnemonic:t})=>{try{return{didWork:!0,quote:await r(t).getClaimStaticDepositQuote(e)}}catch(e){return console.log("Get reusable Bitcoin mainchain address quote error",e),{didWork:!1,error:e.message}}},refundSparkStaticBitcoinL1AddressQuote:async({depositTransactionId:e,destinationAddress:t,fee:n,mnemonic:i})=>{try{return await r(i).refundStaticDeposit({depositTransactionId:e,destinationAddress:t,fee:n})}catch(e){console.log("Refund reusable Bitcoin mainchain address error",e)}},claimnSparkStaticDepositAddress:async({creditAmountSats:e,outputIndex:t,sspSignature:n,transactionId:i,mnemonic:o})=>{try{return{didWork:!0,response:await r(o).claimStaticDeposit({creditAmountSats:e,sspSignature:n,transactionId:i})}}catch(e){return console.log("Claim static deposit address error",e),{didWork:!1,error:e.message}}},getSparkAddress:async({mnemonic:e})=>{try{return{didWork:!0,response:await r(e).getSparkAddress()}}catch(e){return console.log("Get spark address error",e),{didWork:!1,error:e.message}}},sendSparkPayment:async({receiverSparkAddress:e,amountSats:t,mnemonic:n})=>{try{return{didWork:!0,response:await r(n).transfer({receiverSparkAddress:e.toLowerCase(),amountSats:t})}}catch(e){return console.log("Send spark payment error",e),{didWork:!1,error:e.message}}},sendSparkTokens:async({tokenIdentifier:e,tokenAmount:t,receiverSparkAddress:n,mnemonic:i})=>{try{return{didWork:!0,response:await r(i).transferTokens({tokenIdentifier:e,tokenAmount:BigInt(t),receiverSparkAddress:n})}}catch(e){return console.log("Send spark token error",e),{didWork:!1,error:e.message}}},getSparkLightningPaymentFeeEstimate:async({invoice:e,amountSat:t,mnemonic:n})=>{try{return{didWork:!0,response:await r(n).getLightningSendFeeEstimate({encodedInvoice:e.toLowerCase(),amountSats:t})}}catch(e){return console.log("Get spark lightning payment fee estimate error",e),{didWork:!1,error:e.message}}},sendSparkLightningPayment:async({invoice:e,amountSat:t,mnemonic:n,maxFeeSats:i})=>{try{return{didWork:!0,paymentResponse:await r(n).payLightningInvoice({invoice:e.toLowerCase(),maxFeeSats:i,amountSatsToSend:t})}}catch(e){return console.log("Send spark lightning payment error",e),{didWork:!1,error:e.message}}},sendSparkBitcoinPayment:async({onchainAddress:e,exitSpeed:t,amountSats:n,feeQuote:i,deductFeeFromWithdrawalAmount:o,mnemonic:s})=>{try{return{didWork:!0,response:await r(s).withdraw({onchainAddress:e,exitSpeed:t,amountSats:n,feeQuote:i,deductFeeFromWithdrawalAmount:o})}}catch(e){return console.log("Send spark bitcoin payment error",e),{didWork:!1,error:e.message}}},receiveSparkLightningPayment:async({amountSats:e,memo:t,expirySeconds:n,mnemonic:i})=>{try{return{didWork:!0,response:await r(i).createLightningInvoice({amountSats:e,memo:t,expirySeconds:n})}}catch(e){return console.log("Receive spark lightning payment error",e),{didWork:!1,error:e.message}}},getSparkLightningPaymentStatus:async({lightningInvoiceId:e,mnemonic:t})=>{try{return await r(t).getLightningReceiveRequest(e)}catch(e){console.log("Get spark lightning payment status error",e)}},getSparkBitcoinPaymentRequest:async({paymentId:e,mnemonic:t})=>{try{return await r(t).getCoopExitRequest(e)}catch(e){console.log("Get spark bitcoin payment request error",e)}},getSparkBitcoinPaymentFeeEstimate:async({withdrawalAddress:e,amountSats:t,mnemonic:n})=>{try{return{didWork:!0,response:await r(n).getWithdrawalFeeQuote({amountSats:t,withdrawalAddress:e})}}catch(e){return console.log("Get spark bitcoin payment fee estimate error",e),{didWork:!1,error:e.message}}},getSparkPaymentFeeEstimate:async({amountSats:e,mnemonic:t})=>{try{return await r(t).getSwapFeeEstimate(e)}catch(e){return console.log("Get spark payment fee estimate error",e),0}},getSparkLightningSendRequest:async({id:e,mnemonic:t})=>{try{return await r(t).getLightningSendRequest(e)}catch(e){console.log("Get spark lightning send request error",e)}},getSparkTransactions:async({transferCount:e,offsetIndex:t,mnemonic:n})=>{try{const i=await r(n).getTransfers(e,t);return{transfers:i.transfers.map(e=>(delete e.leaves,e)),offset:i.offset}}catch(e){return console.log("Get spark transactions error",e),{transfers:[]}}},getSparkTokenTransactions:async({ownerPublicKeys:e,issuerPublicKeys:t,tokenTransactionHashes:n,tokenIdentifiers:i,outputIds:o,mnemonic:s,lastSavedTransactionId:a})=>{try{const c=await r(s).queryTokenTransactions({ownerPublicKeys:e,issuerPublicKeys:t,tokenTransactionHashes:n,tokenIdentifiers:i,outputIds:o}),u=c.tokenTransactionsWithStatus.map(e=>{const t=e.tokenTransaction,n=t.tokenOutputs?.[0];return{tokenTransactionHash:e.tokenTransactionHash,tokenTransaction:{clientCreatedTimestamp:t.clientCreatedTimestamp,tokenOutputs:n?[{ownerPublicKey:n.ownerPublicKey,tokenIdentifier:n.tokenIdentifier,tokenAmount:n.tokenAmount}]:[]}}});let d=u;if(a){const e=u.findIndex(e=>sI.from(Object.values(e.tokenTransactionHash)).toString("hex")===a);-1!==e&&(d=u.slice(0,e))}return{tokenTransactionsWithStatus:d,offset:c.offset}}catch(e){return console.log("Get spark transactions error",e),[]}},findTransactionTxFromTxHistory:async({sparkTxId:e,previousOffset:t=0,previousTxs:n=[],mnemonic:i})=>{try{const o=n.find(t=>t.id===e);if(o)return console.log("Using cache tx history"),{didWork:!0,offset:t,foundTransfers:n,bitcoinTransfer:o};const s=r(i);let a,c=t,u=[];const d=20;for(;ct.id===e);if(n){a=n;break}if(-1===t.offset){console.log("Reached end of transactions (offset: -1)");break}c+=1}return{didWork:!0,offset:c,foundTransfers:u,bitcoinTransfer:a}}catch(e){return console.log("Error finding bitcoin tx from history",e),{didWork:!1,error:e.message}}}}};var cI=s(8287).hp;!function(e){let t=aI({sharedKey:null,ReactNativeWebView:window.ReactNativeWebView}),n=null;const r=new Set;let i=0,o=!1,s=!1;async function a(a){try{if("string"!=typeof a.data)return;const c=Date.now();let u=JSON.parse(a.data);if(u.isResponse)return;if(u.id&&r.has(u.id))return void console.log(`Duplicate message ID ${u.id} ignored`);if(!window.__STARTUP_NONCE__||"__INJECT_NONCE__"===window.__STARTUP_NONCE__)throw new Error("Security error: Startup nonce not properly injected");if("handshake:init"===u?.action&&u?.args?.pubN){if(o)throw new Error("Handshake already complete, ignoring subsequent attempt");if(s)throw new Error("Handshake already in progress, ignoring subsequent attempt");s=!0;const a=await async function(){const e=function(e=32){const t="object"==typeof globalThis?globalThis.crypto:null;if("function"!=typeof t?.getRandomValues)throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}(32);return{privateKey:e,publicKey:zx(e,!0)}}();n=iI(a.privateKey,u.args.pubN,window.__STARTUP_NONCE__),t=aI({sharedKey:n,ReactNativeWebView:window.ReactNativeWebView});const c={id:u.id,success:!0,type:"handshake:reply",pubW:cI.from(a.publicKey).toString("hex"),runtimeNonce:await oI(n,window.__STARTUP_NONCE__),isResponse:!0};return console.log("Session key established with native"),r.add(u.id),o=!0,i=1,void e.postMessage(JSON.stringify(c))}if(!o)throw new Error("Received message before handshake complete");if(u.encrypted){const e=await async function(e,t){try{if(!t.includes("?iv=")||!t.includes("&tag="))throw new Error("Missing IV or auth tag");const[n,r]=t.split("?iv="),[i,o]=r.split("&tag="),s=tI.from(i,"base64"),a=tI.from(n,"base64"),c=tI.from(o,"base64"),u=(0,ux.aes256gcm)(e,s),d=new Uint8Array([...a,...c]),f=u.decrypt(d);return(new TextDecoder).decode(f)}catch(e){throw console.log("Web decryptMessage err",e),e}}(n,u.encrypted);u=JSON.parse(e)}if(u.id&&r.has(u.id))return void console.log(`Duplicate message ID ${u.id} ignored`);if("number"==typeof u.sequence){if(u.sequence3e4+(document.hidden?18e4:0))throw new Error(`SECURITY: Rejected stale message: ${e}ms old`);if(e<-5e3)throw new Error(`SECURITY: Rejected future message: ${e}ms in future`)}if(r.add(u.id),"simulate_crash"===u.action)throw new Error("Crash simulation not allowed in production");if(!t[u.action])throw new Error(`Unknown Spark action: ${u.action}`);const d=await t[u.action](u.args),f={id:u.id,success:!0,result:JSON.stringify(d),isResponse:!0};u=null;const l=await oI(n,JSON.stringify(f));e.postMessage(JSON.stringify({encrypted:l,isResponse:!0}))}catch(t){if(console.log("Spark WebContext error:",t),n){const r=await oI(n,JSON.stringify({error:t.message}));e.postMessage(JSON.stringify({encrypted:r,isResponse:!0}))}}}window.addEventListener("message",a),document.addEventListener("message",a),document.addEventListener("securitypolicyviolation",async function(e){const t={type:"security:csp-violation",blocked:e.blockedURI,directive:e.violatedDirective,sourceFile:e.sourceFile,lineNumber:e.lineNumber};if(console.error("CSP VIOLATION:",t),n){const e=await oI(n,JSON.stringify(t));window.ReactNativeWebView?.postMessage(JSON.stringify({encrypted:e,isResponse:!0}))}else window.ReactNativeWebView?.postMessage(JSON.stringify({...t,isResponse:!0,unencrypted:!0}))})}(window.ReactNativeWebView)})()})();